package cdu.bbs.bbsv2.controller;

import cdu.bbs.bbsv2.domain.Topic;
import cdu.bbs.bbsv2.domain.User;
import cdu.bbs.bbsv2.service.TopicService;
import cdu.bbs.bbsv2.service.UserService;
import cdu.bbs.bbsv2.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService ;
    @Resource
    private TopicService topicService;
    @RequestMapping("/login")
    @ResponseBody
    public Map<String, Object> login(HttpServletRequest request, User u){
        u.setLoginPwd(MD5Util.getMD5(u.getLoginPwd()));// 密码加密

        String verifyCode = (String) request.getSession().getAttribute("verifyCode");
        String inputVerifyCode = request.getParameter("verifyCode");

        Map<String,Object> map = new HashMap<String, Object>();
        if(!verifyCode.equals(inputVerifyCode)){
            map.put("success",false);
            map.put("msg", "验证码错误");
            return map;
        }
        User user = userService.login(u.getLoginAct(),u.getLoginPwd());

        if(user == null) { // 未查找到用户
            map.put("success",false);
            map.put("msg", "账号或密码不正确");
        }else if("0".equals(user.getLockState())){  // 账号被锁定
            map.put("success",false);
            map.put("msg", "该账号已被锁定");
        }else {     // 登录成功
            request.getSession().setAttribute("user", user);
            System.out.println(user);
            map.put("success",true);
        }
        return map;
    }

    @RequestMapping("/getUserByCondition")
    private void getUsersByCondition(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String loginAct = request.getParameter("loginAct");
        String email = request.getParameter("email");
        Map<String ,String> conditions = new LinkedHashMap<>();
        //if(!"".equals(name) &&name !=null){
        //    conditions.put("name",name);
        //}if(!"".equals(loginAct) &&loginAct!=null){
        //    conditions.put("loginAct",loginAct);
        //}if(!"".equals(email) &&email!=null){
        //    conditions.put("email",email);
        //}
        //在mybatis中判空处理
        conditions.put("name",name);
        conditions.put("loginAct",loginAct);
        conditions.put("email",email);
        List<User> users = userService.getUsersByCondition(conditions);
        if(users != null){
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("success",true);
            map.put("users",users);
            PrintJson.printJsonObj(response,map);
        }else {;
            PrintJson.printJsonFlag(response,false);
        }
    }

    @RequestMapping("/getVerifyCode")
    private void getVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        int width=200;
        int height=69;
        BufferedImage verifyImg=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        String randomText = VerifyCode.drawRandomText(width,height,verifyImg);
        request.getSession().setAttribute("verifyCode", randomText);
        System.out.println(randomText);
        response.setContentType("image/png");//必须设置响应内容类型为图片，否则前台不识别
        try {
            OutputStream os = response.getOutputStream(); //获取文件输出流
            ImageIO.write(verifyImg,"png",os);//输出图片流
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/register")
    @ResponseBody
    private Map<String, Object> register(User u, HttpServletRequest request, HttpServletResponse response) {
        u.setId(UUIDUtil.getUUID());
        u.setLockState("1");
        u.setCreateTime(DateTimeUtil.getSysTime());
        u.setLoginPwd(MD5Util.getMD5(u.getLoginPwd()));
        String profilePhoto = request.getContextPath()+"/image/touxiang.jpg"; // 默认头像
//        String profilePhoto = request.getServerName()+"/image/touxiang.jpg"; // 默认头像
        u.setProfilePhoto(profilePhoto);

        System.out.println(u);
        boolean flag = false;

        flag = userService.register(u);
        Map<String,Object> map = new HashMap<String, Object>();

        if(flag != false){ // 注册成功
            map.put("success",true);
        }else {
            map.put("success",false);
            map.put("msg", "注册失败");
        }
        return map;

    }

    @RequestMapping("/logout")
    private void logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
        PrintJson.printJsonFlag(response, true);
    }

    @RequestMapping("/main")
    public ModelAndView main(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize){

        Map<Topic, User> topicUserMapTop = topicService.getTopTopicAndUser();// 置顶贴

        PageInfo<Topic> pageInfo =topicService.getNotTop(pageNum,pageSize); // 未置顶帖子

        Map<Topic,User> topicsAndUser = new HashMap<>();
        for (Topic topic:pageInfo.getList()) {
            User user = userService.getUserById(topic.getCreateBy());
            topicsAndUser.put(topic,user);

        }


        System.out.println(topicsAndUser.size());
        Map<String,Object> map = new HashMap();
        map.put("pageInfo",pageInfo);
        map.put("topicsAndUser",topicsAndUser);
        map.put("topicUserMapTop",topicUserMapTop);

        return new ModelAndView("main",map);
    }

    //获取用户自己发布的帖子
    @RequestMapping("/myPushTopic")
    public ModelAndView myPushTopic(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize,HttpServletRequest request){
        String userId=request.getParameter("userId");
        User nowUser=userService.getUserById(userId);
        //获取用户对应的帖子
        PageInfo<Topic> pageInfo = topicService.getTopicsByUserId(pageNum, pageSize, nowUser.getId());
        Map<Topic,User> topicsAndUser = new HashMap<>();
        for (Topic topic:pageInfo.getList()) {
            topicsAndUser.put(topic, nowUser);
        }

        //Map<Topic, User> topicUserMapTop = topicService.getTopTopicAndUser();// 置顶贴

        //PageInfo<Topic> pageInfo =topicService.getNotTop(pageNum,pageSize); // 未置顶帖子
        //
        //Map<Topic,User> topicsAndUser = new HashMap<>();
        //for (Topic topic:pageInfo.getList()) {
        //    User user = userService.getUserById(topic.getCreateBy());
        //    topicsAndUser.put(topic,user);
        //
        //}


        System.out.println(topicsAndUser.size());
        Map<String,Object> map = new HashMap();
        map.put("pageInfo",pageInfo);
        map.put("topicsAndUser",topicsAndUser);
        map.put("user",nowUser);

        return new ModelAndView("myPushTopic",map);
    }
    //获取用户收藏的帖子
    @RequestMapping("/myCollectionTopic")
    public ModelAndView myCollectionTopic(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize,HttpServletRequest request){
        User nowUser=(User) request.getSession().getAttribute("user");
        //获取用户对应的帖子
        PageInfo<Topic> pageInfo = topicService.getCollectionTopicsByUserId(pageNum, pageSize, nowUser.getId());
        Map<Topic,User> topicsAndUser = new HashMap<>();

        for (Topic topic:pageInfo.getList()) {
            User user = userService.getUserById(topic.getCreateBy());
            topicsAndUser.put(topic,user);

        }

        //Map<Topic, User> topicUserMapTop = topicService.getTopTopicAndUser();// 置顶贴

        //PageInfo<Topic> pageInfo =topicService.getNotTop(pageNum,pageSize); // 未置顶帖子
        //
        //Map<Topic,User> topicsAndUser = new HashMap<>();
        for (Topic topic:pageInfo.getList()) {
            User user = userService.getUserById(topic.getCreateBy());
            topicsAndUser.put(topic,user);

        }


        System.out.println(topicsAndUser.size());
        Map<String,Object> map = new HashMap();
        map.put("pageInfo",pageInfo);
        map.put("topicsAndUser",topicsAndUser);

        return new ModelAndView("myCollection",map);
    }
    @RequestMapping("/myThumbTopic")
    public ModelAndView myThumbTopic(@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "5") int pageSize,HttpServletRequest request){
        User nowUser=(User) request.getSession().getAttribute("user");
        //获取用户对应的帖子
        PageInfo<Topic> pageInfo = topicService.getThumbTopicsByUserId(pageNum, pageSize, nowUser.getId());
        Map<Topic,User> topicsAndUser = new HashMap<>();
        for (Topic topic:pageInfo.getList()) {
            User user = userService.getUserById(topic.getCreateBy());
            topicsAndUser.put(topic,user);

        }

        //Map<Topic, User> topicUserMapTop = topicService.getTopTopicAndUser();// 置顶贴

        //PageInfo<Topic> pageInfo =topicService.getNotTop(pageNum,pageSize); // 未置顶帖子
        //
        //Map<Topic,User> topicsAndUser = new HashMap<>();
        //for (Topic topic:pageInfo.getList()) {
        //    User user = userService.getUserById(topic.getCreateBy());
        //    topicsAndUser.put(topic,user);
        //
        //}


        System.out.println(topicsAndUser.size());
        Map<String,Object> map = new HashMap();
        map.put("pageInfo",pageInfo);
        map.put("topicsAndUser",topicsAndUser);

        return new ModelAndView("myThumb",map);
    }

}


